<?php
class User_model extends CI_Model {

	const make_pwd_key = 'n890fIn]b+zCCDsn';
	const make_vcode_key = '{n.(5DD!V#&;Ui~@';
	
//user_id、email、password、name、check_email、role、point、account(账户余额)、count_consume(累计消费)
//第三方登录(网站名和网站id)
//site_name、site_id
    function __construct()
    {
        parent::__construct();
        $this->load->library('email');
    }
    
	public function login($email,$password)
	{
		$sql = 'select * from '.$this->db->dbprefix('user')." where email = '{$email}' LIMIT 1 ";
		$query = $this->db->query($sql);
		$row = $query->row_array();
		if($row['password'] == md5($password)){			
			$this->_login($row['user_id'], $row['email'], $row['role']);
			return $row;
		}
		return false;
		//return $user;	
	}
	
	public function getUser()
	{
		if($this->isLogin())
			return $this->session->userdata();
		else
			return false;
	}
	
	public function getUserId()
	{
		return $this->session->userdata('user_id');
	}
	
	public function logout()
	{
		$userdata['user_id'] = '';
		$userdata['email'] = '';
		$userdata['role'] = '';
		$this->session->unset_userdata($userdata);
	}
	
	public function isLogin()
	{
			return $this->getUserId();
	}
	
	public function simpleRegister($email)
	{
		if($this->checkEmail($email))
		{
			$pwd = md5($email.self::make_pwd_key);
			$user_id = $this->insertUser(array('email'=>$email,'pwd'=>$pwd));
			$user = array(
				'id' => $user_id,
				'email' => $email,				
			);
			$this->_login($user_id, $email, 1);
			//$this->sendCheckEmail($email, $pwd, $user_id);
			return $user;
		}
		return false;
	}
	
	public function verifyEmail($user_id,$vcode)
	{
		$row = $this->getOne($user_id);
		if(!empty($row))
		{
			if($this->makeVCode(array('email'=>$row['email'],'pwd'=>$row['password'],'user_id'=>$user_id,'vcode'=>$vcode)) === true)
			{
				$sql = "UPDATE ".$this->db->dbprefix('user')."  SET `check_email` = '1' WHERE `user_id` =".intval($user_id)." LIMIT 1 ";				
				$this->db->query($sql);				
				if($this->db->affected_rows())
				{
					$this->_login($user_id, $row['email']);
				}
			}
		}
	}
	
	private function makeVCode($data)
	{
		$vcode = '';
		if( isset($data['vcode']))
		{
			$vcode =$data['vcode'];
			unset($data['vcode']);
		}		
		$str = '';
		arsort($data);
		foreach($data as $key=>$d)
		{
			$str .= $key.'='.$d;
		}
		$newvcode = md5($str.self::make_vcode_key);			
		if($vcode == '')
		{
			return $newvcode;
		}
		return $newvcode == $vcode;
	}
	
	private function sendCheckEmail($email,$pwd,$user_id)
	{
		$vcode = $this->makeVCode(array('email'=>$email,'pwd'=>$pwd,'user_id'=>$user_id));		
		$this->email->from('noreply@imore.cc', '艾木iMore');
		$this->email->to($email);		
		$this->email->subject('Email 验证');
		$this->email->message('<a href="?user_id='.$user_id.'&vcode='.$vcode.'">验证链接</a>');		
		$this->email->send();		
		//echo $this->email->print_debugger();
	}
	
	
	
	private function _login($user_id,$email,$role = 1)
	{
		$userdata['user_id'] = $user_id;
		$userdata['email'] = $email;
		$userdata['role'] = $role;
		
		$this->session->set_userdata($userdata);
	}
	
	private function insertUser($data)
	{		
		$sql = "INSERT INTO ".$this->db->dbprefix('user')." (`user_id`, `email`, `password`, `name`, `check_email`, `role`, `point`, `account`, `count_consume`, `site_name`, `site_id`) ";
		$sql .= "VALUES (NULL, ".$this->db->escape($data['email']).", ".$this->db->escape($data['pwd']).", '', '0', '1', '0', '0', '0', 'imore', '0')";
		$this->db->query($sql);
		return $this->db->insert_id();
	}
	//true 没有存在
	//false 已经存在
	public function checkEmail($email)
	{
		$sql = 'select 1 from '.$this->db->dbprefix('user')." where email = '{$email}' LIMIT 1 ";
		$query = $this->db->query($sql);
		$row = $query->row_array();
		return empty($row);		
	}
	
	public function getOne($user_id)
	{
		$user_id = intval($user_id);
		$sql = 'select * from '.$this->db->dbprefix('user')." where user_id = '{$user_id}' LIMIT 1 ";
		$query = $this->db->query($sql);
		$row = $query->row_array();
		return $row;
	}
}